package com.hstx.demo.mqtt.controller;

import com.hstx.demo.mqtt.until.Log;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Controller;

@Controller
public class MqttController {
    private MqttConnectOptions options;
    private MemoryPersistence persistence;
    private MqttClient client;

    private String hostUrl;
    private String clientId;
    private String username;
    private String password;
    private String subscribeTopic;
    private int subscribeQos;
    private MqttRecivePushCallBack callBack;

    /**
     * 创建MQTT连接
     */
    public void connect() {
        // 设置持久化方式
        persistence = new MemoryPersistence();
        try {
            // host为主机名，clientid即连接MQTT的客户端ID，一般以唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(hostUrl, clientId, persistence);
        } catch (MqttException e) {
            e.printStackTrace();
        }
        setOptions();
        // 设置回调
        if (null != client) {
            client.setCallback(callBack);
        }
        // 创建连接
        try {
            client.connect(options);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 断开链接
     */
    public void disConnect() {
        if (null != persistence) {
            try {
                persistence.close();
            } catch (MqttPersistenceException e) {
                e.printStackTrace();
            }
        }
        if (null != client) {
            if (client.isConnected()) {
                try {
                    client.disconnect();
                    client.close();
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 重新链接
     */
    public void reConnect() {
        if(null != client) {
            if (!client.isConnected()) {
                if (null != options) {
                    try {
                        client.connect(options);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.warn(getClass(), "mqttConnectOptions is null");
                }
            } else {
                Log.warn(getClass(), "mqttClient is connect");
            }
        } else {
            connect();
        }
    }

    /**
     * 订阅主题
     */
    public void subTopic() {
        if (null != client && client.isConnected()) {
            try {
                client.subscribe(subscribeTopic, subscribeQos);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        } else {
            Log.error(getClass(), "mqttClient is error");
        }
    }

    /**
     * 清除订阅主题
     */
    public void cleanTopic() {
        if (null != client && client.isConnected()) {
            try {
                client.unsubscribe(subscribeTopic);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        } else {
            Log.error(getClass(), "mqttClient is error");
        }
    }

    public void publishMeaasge(String publishTopic, String message, int publishQos) {
        if (null != client && client.isConnected()) {
            Log.info(getClass(), "发布消息：" + client.isConnected());
            Log.info(getClass(), "发布客户端Id：" + client.getClientId());
            MqttMessage mqttMessage = new MqttMessage();
            mqttMessage.setQos(publishQos);
            mqttMessage.setPayload(message.getBytes());

            MqttTopic topic = client.getTopic(publishTopic);
            if (null != topic) {
                try {
                    MqttDeliveryToken publishTool = topic.publish(mqttMessage);
                    if (!publishTool.isComplete()) {
                        Log.info(getClass(), "消息发布成功！");
                    }
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        } else {
            reConnect();
        }
    }

    /**
     * MQTT的连接参数设置
     */
    private void setOptions() {
        if (null == options) {
            options = new MqttConnectOptions();
        }
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，设置为true表示每次连接到服务器都以新的身份连接
        options.setCleanSession(false);
        // 设置连接的用户名
        options.setUserName(username);
        // 设置连接的密码
        options.setPassword(password.toCharArray());
        // 设置超时时间 单位为秒
        options.setConnectionTimeout(10);
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
        options.setKeepAliveInterval(20);
        //设置断开后重新连接
        options.setAutomaticReconnect(true);

//        MqttTopic topic = client.getTopic(subscribeTopic);
//        //setWill方法，如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息遗嘱
//        options.setWill(topic, "close".getBytes(), subscribeQos, true);
    }

    public void setHostUrl(String hostUrl) {
        if (StringUtils.isEmpty(hostUrl)) {
            hostUrl = "";
        }
        this.hostUrl = hostUrl;
    }

    public void setClientId(String clientId) {
        if (StringUtils.isEmpty(clientId)) {
            clientId = "";
        }
        this.clientId = clientId;
    }

    public void setUsername(String username) {
        if (StringUtils.isEmpty(username)) {
            username = "";
        }
        this.username = username;
    }

    public void setPassword(String password) {
        if (StringUtils.isEmpty(password)) {
            password = "";
        }
        this.password = password;
    }

    public void setSubscribeTopic(String subscribeTopic) {
        if (StringUtils.isEmpty(subscribeTopic)) {
            subscribeTopic = "";
        }
        this.subscribeTopic = subscribeTopic;
    }

    public void setSubscribeQos(Integer subscribeQos) {
        if (null == subscribeQos) {
            subscribeQos = 0;
        }
        this.subscribeQos = subscribeQos;
    }

    public void setCallBack(MqttRecivePushCallBack callBack) {
        this.callBack = callBack;
    }
}
